<template>
    <div class="submit-bug-vulnerability">
        <Modal :mask-closable="false"
            v-model="submitBugModal.show"
            :title="`${isAdd ? '创建' : '修改'}${titleLabelName}`"
            class="my-modal"
            :width="590"
            @on-visible-change="changeVisible">
            <Form 
                ref="formInline"
                :label-width="130"
                :model="formInline" 
                :rules="ruleInline">
                <FormItem prop="name" :label="`${titleLabelName}名称`" key="name">
                    <Input clearable v-model="formInline.name"></Input>
                </FormItem>
                <!-- 修改时，没有网络区域就不要展示了 -->
                <FormItem prop="assetNetworkMeshId" label="网络区域" v-if="isNetworkTarget && ((!isAdd && formInline.assetNetworkMeshId) || isAdd)" key="assetNetworkMeshId">
                    <Select filterable transfer filterable clearable v-model="formInline.assetNetworkMeshId" :disabled="!isAdd"
                        placeholder="" @on-change="changeMesh">
                        <Option 
                            v-for="item in networkMeshList" 
                            :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="assetId" label="资产" v-if="formInline.assetNetworkMeshId" key="assetId">
                    <Select filterable transfer filterable clearable v-model="formInline.assetId" :disabled="!isAdd"
                        placeholder="" @on-change="changeAsset" :loading="loadingAsset" :not-found-text="loadingAsset ? '' : '无匹配数据'">
                        <Option 
                            v-for="item in assetList" 
                            :value="item.id" :key="item.id">{{ item.title }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="port" label="端口" v-if="formInline.assetId && formInline.productId" :rules="[]" key="port">
                    <Select filterable transfer filterable clearable v-model="formInline.port" :disabled="!isAdd"
                        placeholder="" :loading="loadingPort" :not-found-text="loadingPort ? '' : '无匹配数据'">
                        <Option 
                            v-for="item in portList" 
                            :value="Number(item.port)" :key="item.id">{{ item.port }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="port" label="端口" v-if="formInline.assetId && !formInline.productId" :rules="[{ required: true, type: 'number', message: `端口不能为空`, trigger: 'blur,change' }]" key="port-required">
                    <Select filterable transfer filterable clearable v-model="formInline.port" :disabled="!isAdd"
                        placeholder="" :loading="loadingPort" :not-found-text="loadingPort ? '' : '无匹配数据'">
                        <Option 
                            v-for="item in portList" 
                            :value="Number(item.port)" :key="item.id">{{ item.port }}</Option>
                    </Select>
                </FormItem>
                <!-- <FormItem prop="productId" label="产品名称" :rules="!isNetworkTarget ? [{ required: true, message: '产品不能为空', trigger: 'blur,change' }] : []"
                    v-if="formInline.assetId || !isNetworkTarget" key="productId">
                    <Select filterable transfer filterable clearable v-model="formInline.productId" 
                        placeholder="" @on-change="changeProduct" :disabled="!isAdd">
                        <Option 
                            v-for="item in productOptions"
                            :value="item.productId || item.id" :key="item.productId || item.id">{{item.productName || item.name}}({{ item.productVersion || item.version }})</Option>
                    </Select>
                </FormItem> -->
                <!-- 修改时，被测对象是网络，又不存在网络时，只显示产品名称 -->
                <!-- <FormItem label="产品名称" key="productName" v-if="!isAdd && isNetworkTarget && !formInline.assetNetworkMeshId">
                    <Input clearable v-model="formInline.productName" disabled></Input>
                </FormItem>
                <FormItem prop="module" label="所在模块" class="my-form-item" v-if="formInline.productId || !isNetworkTarget" key="module">
                    <Select filterable transfer filterable clearable v-model="formInline.module" placeholder="" 
                        :loading="loadingOptions" :not-found-text="loadingOptions ? '' : '	无匹配数据'">
                        <Option v-for="item in moduleList" :value="item.id" :key="item.id" :label="item.name">
                            <span>{{ item.name }}</span>
                            <span style="float:right;color:#ccc">{{ item.type === 0 ? '部件' : '组件' }}</span>
                        </Option>
                    </Select>
                    <Tooltip 
                        style="margin-left: 10px;" 
                        transfer 
                        max-width="200" 
                        content="请先选择产品"
                        placement="top">
                        <Icon type="ios-alert" class="ios-alert" />
                    </Tooltip>
                </FormItem> -->
                <FormItem prop="step"  label="发现步骤" key="step">
                    <Input v-model="formInline.step" type="textarea" :rows="3"></Input>
                </FormItem>
                <!-- 提交漏洞时独有的参数 -->
                <template v-if="!isBug">
                    <FormItem prop="origin" label="漏洞来源" key="origin">
                        <Select filterable transfer filterable clearable v-model="formInline.origin" placeholder="">
                            <Option value="0">测试</Option>
                            <Option value="1">评估</Option>
                        </Select>
                    </FormItem>
                    <FormItem prop="url" label="漏洞url地址" key="url">
                        <Input clearable v-model="formInline.url"></Input>
                    </FormItem>
                    <FormItem prop="sulotion"  label="解决方法" key="sulotion">
                        <Input v-model="formInline.sulotion" type="textarea" :rows="3"></Input>
                    </FormItem>
                    <FormItem prop="publicVulnerabilityId"  label="关联的公共漏洞" class="my-form-item" key="publicVulnerabilityId">
                        <!-- 需要手动校验一下，不然不清楚为什么校验不准确 -->
                        <public-vulnerability-select-drawer
                            v-model="formInline.publicVulnerabilityId"
                            :multiple="false"
                            ref="publicVulnerabilitySelectDrawer"
                            @input="changePublicVulnerability"></public-vulnerability-select-drawer>
                    </FormItem>
                    <FormItem prop="publicUrl"  label="参考资料地址" key="publicUrl">
                        <Input v-model="formInline.publicUrl" disabled></Input>
                    </FormItem>
                    <div class="inline">
                        <FormItem prop="cvssv2"  label="CVSSV2" key="cvssv2">
                            <Input v-model="formInline.cvssv2" disabled></Input>
                        </FormItem>
                        <FormItem prop="cve"  label="CVE" key="cve">
                            <Input v-model="formInline.cve" disabled></Input>
                        </FormItem>
                    </div>
                    <div class="inline">
                        <FormItem prop="cwe"  label="CWE" key="cwe">
                            <Input v-model="formInline.cwe" disabled></Input>
                        </FormItem>
                        <FormItem prop="tvid"  label="TVID" key="tvid">
                            <Input v-model="formInline.tvid" disabled></Input>
                        </FormItem>
                    </div>
                    <div class="inline">
                        <FormItem prop="cnnvd"  label="CNNVD" key="cnnvd">
                            <Input v-model="formInline.cnnvd" disabled></Input>
                        </FormItem>
                        <FormItem prop="isPlugin"  label="是否危险插件" key="isPlugin">
                            <RadioGroup clearable v-model="formInline.isPlugin">
                                <Radio label="Y" disabled>是</Radio>
                                <Radio label="N" disabled>否</Radio>
                            </RadioGroup>
                        </FormItem>
                    </div>
                    <FormItem prop="value" label="威胁评分" key="value">
                        <Input v-model="formInline.value" type="number" :disabled="(!!formInline.publicVulnerabilityId.length) && formInline.publicVulnerabilityId[0] !== ''"></Input>
                    </FormItem>
                </template>
                <FormItem prop="level" :label="`${isBug ? '缺陷' : '漏洞'}评级`" key="level">
                    <Select filterable transfer filterable clearable v-model="formInline.level" placeholder="" :disabled="!isBug && (!!formInline.publicVulnerabilityId.length) && formInline.publicVulnerabilityId[0] !== ''">
                        <!-- <template v-if="isBug">
                            <Option value="0">建议</Option>
                            <Option value="1">一级</Option>
                            <Option value="2">二级</Option>
                            <Option value="3">三级</Option>
                        </template>
                        <template v-else> -->
                            <Option 
                                v-for="(val, key) in $ConfigurationParameter.VULNERABILITY_LEVEL_OPTIONS"
                                :key="key"
                                :value="key"
                                :title="val">{{ val }}</Option>
                        <!-- </template> -->
                    </Select>
                </FormItem>
                <FormItem prop="disposalPriority" label="处置优先级" v-if="!isBug" key="disposalPriority">
                    <Select filterable transfer filterable clearable v-model="formInline.disposalPriority" placeholder="">
                        <Option 
                            v-for="(val, key) in $ConfigurationParameter.VULNERABILITY_DISPOSAL_PRIORITY_OPTIONS"
                            :key="key"
                            :value="key"
                            :title="val">{{ val }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="fileId"  label="附件" key="fileId">
                    <item-upload
                        @upload-success="bindFile" 
                        @del-item="delFile"
                        fileType="docs"
                        :download="true"
                        :fileList="fileList"
                        :formatArr="['doc','docx']"></item-upload>
                </FormItem>
                <!-- <FormItem prop="testTransactionId"  label="关联事务" v-show="isAdd" key="testTransactionId">
                    <Select filterable transfer filterable clearable v-model="formInline.testTransactionId" placeholder="">
                        <Option v-for="item in testAffairList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="testItemId"  label="关联测试项" v-show="isAdd"
                    key="testItemId"
                    :rules="isAdd ? [{ required: true, message: '关联测试项不能为空', trigger: 'blur,change' }] : []">
                    <Select filterable transfer filterable clearable v-model="formInline.testItemId" placeholder="" @on-change="formInline.testItemCaseId = ''">
                        <Option v-for="item in testItemList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem prop="testItemCaseId"  label="关联测试用例" v-show="isAdd"
                    :rules="isAdd ? [{ required: true, message: '关联测试用例不能为空', trigger: 'blur,change' }] : []"
                    key="testItemCaseId">
                    <Select filterable transfer filterable clearable v-model="formInline.testItemCaseId" placeholder="">
                        <Option v-for="item in testCaseOptions" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem> -->
                <template v-if="!isBug && isAdd">
                    <FormItem prop="teamId" label="测试组" key="teamId">
                        <Select filterable 
                            v-model="formInline.teamId" 
                            filterable
                            clearable
                            placeholder=""
                            class="my-select"
                            @on-change="changeUserGroup">
                            <Option v-for="item in userGroup" :key="item.id" :value="item.id">{{ item.name }}</Option>
                        </Select>
                    </FormItem>
                    <FormItem prop="userIds" label="验证人员" key="userIds">
                        <Transfer
                            class="my-transfer"
                            :data="userList"
                            :target-keys="formInline.userIds"
                            :titles="['可选人员', '已选人员']"
                            @on-change="handleChange"></Transfer>
                    </FormItem>
                    <FormItem prop="sendType" label="通知方式" key="sendType">
                        <RadioGroup v-model="formInline.sendType">
                            <Radio :label="1" disabled>系统内信息</Radio>
                            <Radio :label="2">邮件</Radio>
                            <Radio :label="3" disabled>工单系统</Radio>
                            <Radio :label="4" disabled>短信</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem prop="description1"  label="复测要求" key="description1">
                        <Input v-model="formInline.description1" type="textarea" :rows="3"></Input>
                    </FormItem>
                </template>
                <FormItem prop="description"  label="描述" key="description">
                    <Input v-model="formInline.description" type="textarea" :rows="3"></Input>
                </FormItem>
            </Form>
            <div slot="footer" class="footer">
				<Button @click="submitBugModal.show = false">取消</Button>
                <Button v-if="generateEmail" @click="generateEmailBtn" type="primary">生成邮件</Button>
                <Button v-else @click="saveBugOrVulnerability" :loading="emailModal.loading" type="primary">确定</Button>
            </div>
        </Modal>
        <Modal :mask-closable="false"
            v-model="emailModal.show"
            title="邮件内容"
            @on-visible-change="emailModal.loading = false">
            <div style="display: flex;">
                <label style="width: 80px;">复测邮件</label>
                <email-content 
                    v-model="formInline.mailRepairer"
                    :isBug="isBug"
                    :productName="productName"
                    :vulnerabilityName="formInline.name"
                    :module="moduleName"
                    :url="formInline.url"
                    :level="formInline.level"
                    :score="formInline.value"
                    :description="formInline.description"
                    :sulotion="formInline.sulotion"
                    :publicUrl="formInline.publicUrl"
                    ref="emailContent"></email-content>
            </div>
            <div slot="footer" class="footer">
				        <Button @click="emailModal.show = false">取消</Button>
                <Button @click="saveBugOrVulnerability" :loading="emailModal.loading" type="primary">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import { queryAssetList, queryAssetServiceList, queryProductPartList, addBug, updateBug, getProductByAsset, saveCreateVulnerability, updCreateVulnerability } from '@/view/testPlatform/asset/api/leak.js'
import ItemUpload from '@/view/testPlatform/components/item-upload/index.vue'
import InfoPoptip from '@/view/testPlatform/components/info-poptip/index.vue'
import PublicVulnerabilitySelectDrawer from '@/view/testPlatform/components/public-vulnerability-select-drawer'
import { validateIp } from '@/libs/reg' 

export default {
    name: 'SubmitBug',
    components: {
        ItemUpload,
        InfoPoptip,
        PublicVulnerabilitySelectDrawer,
    },
    computed: {
        titleLabelName() {
            return this.isBug ? '缺陷' : '漏洞'
        },
        testCaseOptions() {
            return this.formInline.testItemId ? this.testCaseList.filter(item => item.testItemId === this.formInline.testItemId) : this.testCaseList
        },
        productOptions() {
            if (this.isNetworkTarget) {
                return this.selfProducts
            } else {
                return this.targetList
            }
        },
        // 创建漏洞的时候，需要生成邮件
        generateEmail() {
            return !this.isBug && this.isAdd
        },
        productName() {
            let template = this.productOptions.find(item => item.productId === this.formInline.productId || item.id === this.formInline.productId) || {}
            return template.productName || template.name
        },
        moduleName() {
            let template = this.moduleList.find(item => item.id === this.formInline.module) || {}
            return template.name
        }
    },
    watch: {
        'formInline.level': function(val) {
            if (!val) {
                return
            }
            this.formInline.disposalPriority = (String(Number(val) + 1))
        }
    },
    props: {
        networkId: {
            type: String,
            default: ''
        },
        networkMeshList: {
            type: Array,
            default: () => []
        },
        userGroup: {
            type: Array,
            default: () => []
        },
        testProjectId: {
            type: String,
            default: ''
        },
        isNetworkTarget: {
            type: Boolean,
            default: false
        },
        isBug: {
            type: Boolean,
            default: true
        },
        targetList: {
            type: Array,
            default: () => []
        },
        testCaseList: {
            type: Array,
            default: () => []
        },
        testItemList: {
            type: Array,
            default: () => []
        },
        testAffairList: {
            type: Array,
            default: () => []
        },
        module: {
            type: String,
            default: ''
        },
        productId: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            emailModal: {
                show: false,
                loading: false
            },
            loadingOptions: false,
            submitBugModal: {
                show: false,
                loading: false
            },
            formInline: {
                description1: '',
                assetNetworkMeshId: '',
                assetId: '',
                mailRepairer: '',
                sendType:2,
                teamId: '',
                userIds: [],
                name: '',
                testProjectId: this.testProjectId,
                productId: this.productId,
                module: this.module,
                description: '',
                step: '',
                sulotion: '',
                level: '',
                disposalPriority: '',
                fileId: '',
                fileName: '',
                testItemCaseId: '',
                testTransactionId: '',
                testTransactionName: '',
                testItemId: '',
                publicVulnerabilityId: [],
                publicUrl: '',
                cvssv2: '',
                cve: '',
                cwe: '',
                tvid: '',
                cnnvd: '',
                isPlugin: 'Y',
                value: '',
                creatorName: this.$store.state.user.nickName,
                status: '1',
                origin: '',
                url: '',
                ip: '',
                port: '',
                networkId: this.networkId
            },
            ruleInline: {
                description1: [
                    { required: true, message: '复测要求不能为空', trigger: 'blur,change' },
                ],
                teamId: [
                    { required: true, message: '此项不能为空', trigger: 'blur,change' },
                ],
                userIds: [
                    { required: true, type: 'array', message: '此项不能为空', trigger: 'blur,change' },
                ],
                sendType:[
                    { type:'number',trigger:'blur,change',message:'通知方式不能为空' }
                ],
                name: [
                    { required: true, message: `名称不能为空`, trigger: 'blur,change' },
                    { type: 'string', max: 200, message: '最多输入200个字符', trigger: 'blur,change' },
                ],
                module: [
                    // { required: true, message: '所在模块不能为空', trigger: 'blur,change' }
                ],
                step: [
                    { type: 'string', max: 1000, message: '最多输入1000个字符', trigger: 'blur,change' },
                ],
                sulotion: [
                    { type: 'string', max: 1000, message: '最多输入1000个字符', trigger: 'blur,change' },
                ],
                publicVulnerabilityId: [
                ],
                level: [
                    { required: true, message: `${this.isBug ? '缺陷' : '漏洞'}评级不能为空`, trigger: 'blur,change' }
                ],
                disposalPriority: [
                    { required: true, message: '处置优先级不能为空', trigger: 'blur,change' }
                ],
                publicUrl: [
                    { type:'string',max: 65535,trigger:'blur,change',message:'最多输入65535个字符' },
                ],
                origin: [
                    { required: true, message: `漏洞来源不能为空`, trigger: 'blur,change' },
                ],
                url: [
                    { type:'string',max: 65535,trigger:'blur,change',message:'最多输入65535个字符' },
                ],
                ip: [
                    { required: true, message: `IP不能为空`, trigger: 'blur,change' },
                    { validator: validateIp, trigger: 'blur,change' }
                ],
                assetNetworkMeshId: [
                    { required: true, message: `网络区域不能为空`, trigger: 'blur,change' },
                ],
                assetId: [
                    { required: true, message: `资产不能为空`, trigger: 'blur,change' },
                ],
            },
            isAdd: false,
            fileList: [],
            moduleList: [],
            userList: [],
            loadingAsset: false,
            assetList: [],
            loadingPort: false,
            loadingProduct: false,
            selfProducts: [] // 被测对象是网络时，需要通过选择资产，自动获取可选的产品，不再是有props中传入的数据
        }
    },
    mounted(){
    },
    methods: {
        // 选择可选人员
        handleChange (newTargetKeys) {
            this.formInline.userIds = newTargetKeys;
        },
        // 修改测试组，重置人员可选项和已选项
        changeUserGroup(id) {
            this.formInline.userIds = []
            if (!id) {
                this.userList = []
                return
            }
            let template = this.userGroup.find(item => item.id === id) || {}
            // 过滤掉第三方的用户
            this.userList = (template.users || []).filter(f=>f.thirdParty === 0).map(item => {
                return {
                    key: item.userId,
                    label: item.userName,
                    userId: item.userId
                }
            })
        },
        // 修改资产时，查询可选端口
        changeAsset(assetId, unset) {
            this.portList = []
            if (!unset) {
                this.formInline.port = ''
                this.formInline.productId = ''
            }
            if (!assetId) {
                this.formInline.ip = ''
                return
            }
            this.formInline.ip = (this.assetList.find(item => item.id === assetId) || {}).ip
            this.loadingPort = true
            queryAssetServiceList({
                pageIndex: 1,
                pageSize: 2147483647,
                assetId
            }).then(({ data = {} }) => {
                let { code, message } = data
                data = data.data || {}
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.portList = data.items || []
            }).finally(() => {
                this.loadingPort = false
            })
            this.loadingProduct = true
            getProductByAsset({
                assetIdList: assetId
            }).then(({ code, message, data = {} }) => {
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.selfProducts = data || []
            }).finally(() => {
                this.loadingProduct = false
            })
        },
        // 修改网络区域时，查询可选资产
        changeMesh(assetNetworkMeshId, unset) {
            if (!unset) {
                this.formInline.assetId = ''
                this.formInline.port = ''
                this.formInline.ip = ''
                this.formInline.productId = ''
            }
            this.assetList = []
            if (!assetNetworkMeshId) {
                return
            }
            this.loadingAsset = true
            queryAssetList({
                pageIndex: 1,
                pageSize: 2147483647,
                assetNetworkMeshId: assetNetworkMeshId
            }).then(({ data = {} }) => {
                let { code, message } = data
                data = data.data || {}
                if (code !== 1) {
                    this.$Message.warning(message)
                    return
                }
                this.assetList = data.items || []
            }).finally(() => {
                this.loadingAsset = false
            })
        },
        //  改变产品后，查询产品关联的部件和组件
        changeProduct(productId, unreset) {
            this.moduleList = []
            if (!unreset) {
                this.formInline.module = ''
            }
            if (!productId) {
                return
            }
            this.loadingOptions = true
            Promise.all([queryProductPartList({
                pageIndex: 1,
                pageSize: 2147483647,
                productId,
            })
            // , queryProductComponentList({
            //     pageIndex: 1,
            //     pageSize: 2147483647,
            //     productId,
            // })
            ]).then(resList => {
                let list = []
                resList.forEach(({ data = {} }, index) => {
                    if (data.code === 1) {
                        (data.data.items || []).forEach(item => {
                            list.push({
                                id: item.id,
                                name: item.name,
                                type: index,
                            })
                        })
                    }
                })
                this.moduleList = list
            }).finally(() => {
                this.loadingOptions = false
            })
        },
        changePublicVulnerability() {
            this.$nextTick(() => {
                this.$refs.formInline.validateField('publicVulnerabilityId')
                let template = this.$refs.publicVulnerabilitySelectDrawer && this.$refs.publicVulnerabilitySelectDrawer.getSelectedValue()
                if (template) {
                    template = template[0] || {}
                    this.$set(this.formInline, 'publicUrl', template.publicUrl || '')
                    this.$set(this.formInline, 'cvssv2', template.cvssv2 || '')
                    this.$set(this.formInline, 'cve', template.cve || '')
                    this.$set(this.formInline, 'cwe', template.cwe || '')
                    this.$set(this.formInline, 'tvid', template.tvid || '')
                    this.$set(this.formInline, 'cnnvd', template.cnnvd || '')
                    this.$set(this.formInline, 'isPlugin', template.isPlugin || 'N')
                    this.$set(this.formInline, 'value', template.value || 0)
                    this.$set(this.formInline, 'level', template.level || '')
                } else {
                    this.$set(this.formInline, 'publicUrl', '')
                    this.$set(this.formInline, 'cvssv2', '')
                    this.$set(this.formInline, 'cve', '')
                    this.$set(this.formInline, 'cwe', '')
                    this.$set(this.formInline, 'tvid', '')
                    this.$set(this.formInline, 'cnnvd', '')
                    this.$set(this.formInline, 'isPlugin', 'N')
                    this.$set(this.formInline, 'value', 0)
                    this.$set(this.formInline, 'level', '')
                }
            })
        },
        // 上传文件成功后绑定数据
        bindFile(file) {
            this.fileList = [(Object.assign(file, { id: file.fileId }))]
            this.formInline.fileId = file.fileId
            this.formInline.fileName = file.fileName
            this.formInline.filePath = file.filePath
        },
        // 删除文件成功后解绑数据
        delFile(fileId) {
            let index = this.fileList.findIndex(item => item.id === fileId)
            if (index !== -1) {
                this.fileList.splice(index, 1)
                this.formInline.fileId = ''
                this.formInline.fileName = ''
                this.formInline.filePath = ''
            }
        },
        // 隐藏模态框时，重置表单数据
        changeVisible(type) {
            this.$nextTick(() => {
                if (!type) {
                    this.fileList = []
                    this.formInline.fileId = ''
                    this.formInline.fileName = ''
                    this.formInline.filePath = ''
                    this.emailModal.loading = false
                    // 延迟200毫秒再修改并重置表单，免得在模态框隐藏动画过程中就出现校验信息，测试又要提bug了
                    setTimeout(() => {
                        this.formInline.publicVulnerabilityId = []
                        this.$nextTick(() => {
                            this.$refs.formInline.resetFields()
                        })
                        this.$refs.publicVulnerabilitySelectDrawer && this.$refs.publicVulnerabilitySelectDrawer.clear()
                    }, 200)
                }
            })
        },
        generateEmailBtn() {
            this.$refs.formInline.validate(valid => {
                if (valid) {
                    this.emailModal.show = true
                    this.$nextTick(() => {
                        this.$refs.emailContent.setContent()
                    })
                }
            })
        },
        // 保存缺陷或者漏洞
        saveBugOrVulnerability() {
            this.$refs.formInline.validate(valid => {
                if (valid) {
                    this.emailModal.loading = true
                    let apiName = this.isAdd 
                        ? (this.isBug ? addBug : saveCreateVulnerability)
                        : (this.isBug ? updateBug : updCreateVulnerability)
                    if (this.isAdd) { // 创建操作确认把id删掉，避免造成错误
                        delete this.formInline.id
                    }
                    let params = JSON.parse(JSON.stringify(this.formInline))
                    if (params.publicVulnerabilityId && params.publicVulnerabilityId.length) {
                        let str = params.publicVulnerabilityId[0]
                        params.publicVulnerabilityId = str
                    } else {
                        params.publicVulnerabilityId = ''
                    }
                    // 添加漏洞时，需要设置复测信息的数据
                    if (this.isAdd && !this.isBug) {
                        params.testRestart = {
                            validateRequire: params.description1,
                            verifyMailRepairer: params.mailRepairer,
                            testProjectId: this.testProjectId,
                            type: this.isBug ? 1 : 2,
                            verifySendType: params.sendType,
                        }
                        params.verifyRestartAllotList = params.userIds.map(userId => {
                            return {
                                teamId: params.teamId,
                                userId,
                                type: 1
                            }
                        })
                        params.testVulnerabilityLog = {
                            assetId: params.assetId,
                            assetNetworkMeshId: params.assetNetworkMeshId,
                            level: params.level,
                            networkId: this.networkId,
                            origin: params.origin,
                            testProjectId: this.testProjectId,
                        }
                    }
                    apiName(params).then(({ code, message, data = {} }) => {
                        // 有些接口的返回可能多包了一层，做兼容处理
                        if (code === undefined && data.code !== undefined) {
                            code = data.code
                            message = data.message
                        }
                        if (code !== 1) {
                            this.$Message.warning(message)
                            return
                        }
                        // 创建成功
                        if (!this.noMessage) {
                            this.$Message.success(`${this.isAdd ? '创建' : '修改'}${this.titleLabelName}成功`)
                        }
                        this.$emit(this.isAdd ? 'add-succee' : 'update-succee')
                        this.submitBugModal.show = false
                        this.emailModal.show = false
                    }).catch(() => {
                        this.$Message.error(`${this.isAdd ? '创建' : '修改'}${this.titleLabelName}异常`)
                    }).finally(() => {
                        this.emailModal.loading = false
                    })
                }
            })
        },
        // 打开保存缺陷或者漏洞的模态框
        showModal(testTransactionId, testTransactionName, data, isAdd, noMessage) {
            this.submitBugModal.show = true
            if (testTransactionId) {
                this.formInline.testTransactionId = testTransactionId
                this.formInline.testTransactionName = testTransactionName
            }
            if (data) {
                data.publicVulnerabilityId = [data.publicVulnerabilityId]
                this.changeProduct(data.productId, true)
                // testProjectId不能为空，最后设置，避免被覆盖
                this.formInline = Object.assign({}, data, {
                    testProjectId: this.testProjectId,
                    networkId: this.networkId
                })
                this.$set(this.formInline, 'testItemId', data.testItemId)
                this.$set(this.formInline, 'testItemCaseId', data.testItemCaseId)
                this.$set(this.formInline, 'port', Number(data.port))
                if (data.fileId) {
                    this.fileList = [{
                        fileId: data.fileId,
                        fileName: data.fileName,
                        filePath: data.filePath,
                        id: data.fileId
                    }]
                }
                let testVulnerabilityLog = data.testVulnerabilityLog || {}
                this.$set(this.formInline, 'assetNetworkMeshId', testVulnerabilityLog.assetNetworkMeshId)
                this.changeMesh(testVulnerabilityLog.assetNetworkMeshId, true)
                this.$nextTick(() => {
                    this.$set(this.formInline, 'assetId', testVulnerabilityLog.assetId)
                    this.changeAsset(testVulnerabilityLog.assetId, true)
                })
            } else {
                this.formInline = {
                    description1: '',
                    assetNetworkMeshId: '',
                    assetId: '',
                    mailRepairer: '',
                    sendType:2,
                    teamId: '',
                    userIds: [],
                    name: '',
                    testProjectId: this.testProjectId,
                    productId: this.productId,
                    module: this.module,
                    description: '',
                    step: '',
                    sulotion: '',
                    level: '',
                    disposalPriority: '',
                    fileId: '',
                    fileName: '',
                    testItemCaseId: '',
                    testTransactionId: '',
                    testTransactionName: '',
                    testItemId: '',
                    publicVulnerabilityId: [],
                    publicUrl: '',
                    cvssv2: '',
                    cve: '',
                    cwe: '',
                    tvid: '',
                    cnnvd: '',
                    isPlugin: 'Y',
                    value: '',
                    creatorName: this.$store.state.user.nickName,
                    status: '1',
                    origin: '',
                    url: '',
                    ip: '',
                    port: '',
                    networkId: this.networkId
                }
            }
            // 不存在data数据为创建操作，否则为修改操作
            this.isAdd = isAdd || !data // 当isAdd为真时，存在data数据，但是仍然是创建操作
            this.noMessage = noMessage
            if (this.formInline.publicVulnerabilityId) {
                this.$refs.publicVulnerabilitySelectDrawer && this.$refs.publicVulnerabilitySelectDrawer.getCheckList(this.formInline.publicVulnerabilityId.join(','))
            }
        }
    }
}
</script>

<style scoped>
.inline {
    display: flex;
}
.inline /deep/ .ivu-form-item {
    width: 50%;
}
.my-select /deep/ .ivu-select-dropdown {
    width: 352px;
}
.my-scroll /deep/ .ivu-scroll-container {
    height: fit-content !important;
    max-height: 190px;
}
.my-form-item {
    position: relative;
}
.my-form-item /deep/ .ivu-form-item-content {
    display: flex;
}
.my-form-item /deep/ .ios-alert {
    color: orange;
    font-size: 16px;
    cursor: pointer;
}
</style>